package project.web;

import Utils.io.json.JacksonUtils;
import Utils.web.servlet.BaseServlet;
import Utils.web.WebUtils;
import project.pojo.User;
import project.service.UserService;
import project.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author d11yu
 */
@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    /**
     * 用户注册
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, InvocationTargetException, IllegalAccessException, SQLException {
        // 获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");
        String repwd = request.getParameter("repwd");

        User user = WebUtils.copyParamsToBean(request.getParameterMap(), User.class);
        // 检查验证码是否正确（写死，要求验证码为"abcde"）
        String token = WebUtils.getKaptchaToken(request);
        if (token != null && token.equalsIgnoreCase(code)) {
            System.out.println("验证码[" + code + "]正确！");

            if (userService.exists(user)) {
                request.setAttribute("msg", "用户名已经存在！");
                request.getRequestDispatcher("pages/user/regist.jsp").forward(request, response);
            } else {
                User registerUser = userService.register(user);
                user.setId(registerUser.getId());
                request.getSession().setAttribute("user", user);
                request.getRequestDispatcher("pages/user/regist_success.jsp").forward(request, response);
            }
        } else {
            request.setAttribute("msg", "验证码错误！");
            request.setAttribute("username", username);
            request.setAttribute("email", email);
            request.setAttribute("password", password);
            request.setAttribute("repwd", repwd);
            request.getRequestDispatcher("pages/user/regist.jsp").forward(request, response);
        }
    }

    /**
     * 用户登录
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, InvocationTargetException, IllegalAccessException, SQLException {
        String username = request.getParameter("username");
        User user = WebUtils.copyParamsToBean(request.getParameterMap(), User.class);
        User loginUser = userService.login(user);
        if (loginUser == null) {
            // 把错误信息返回给网页
            request.setAttribute("msg", "用户或密码错误！");
            request.setAttribute("username", username);
            request.getRequestDispatcher("pages/user/login.jsp").forward(request, response);
        } else {
            user.setId(loginUser.getId());
            request.getSession().setAttribute("user", user);
            request.getRequestDispatcher("pages/user/login_success.jsp").forward(request, response);
        }
    }

    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        WebUtils.terminateSession(request);
        response.sendRedirect(request.getContextPath());
    }
    
    protected void exitsAjaxUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String username = request.getParameter("username");
        Map<String, Object> resultMap=new HashMap<>();
        resultMap.put("exitsAjaxUsername", userService.exists(username));
        response.getWriter().write(JacksonUtils.getInstance().serialize(resultMap));
    }
}
